import React from 'react'
// 导入样式
import styles from './index.module.css'
// 导入校验规则
import PropTypes from 'prop-types'
class Sticky extends React.Component {
    constructor(props) {
        super(props)
        this.placeholder = React.createRef()
        this.content = React.createRef()
    }
    
    handleScroll = () => {
        // 获取DOM对象
        const placeholderEl = this.placeholder.current
        const contentEl = this.content.current
        const {top} = placeholderEl.getBoundingClientRect() 
        const {height} = this.props
        // 判断
        if (top < 0) {
            // 大于吸顶
            contentEl.classList.add(styles.fixed)
            placeholderEl.style.height = `${height}px`
        } else {
            // 小于取消吸顶
            contentEl.classList.remove(styles.fixed)
            placeholderEl.style.height = '0px'
        }
        
    }
    // 加载组件是调用的方法
    componentDidMount() {
        window.addEventListener('scroll',this.handleScroll)
    }
    // 卸载组件时调用的方法
    componentWillUnmount() {
        window.removeEventListener('scroll',this.handleScroll)
    }
    render() {
        return (
            <div>
                {/* 占位符 */}
                <div ref={this.placeholder}/>
                {/* 内容元素 */}
                <div ref={this.content}>{this.props.children}</div>
            </div>
        )
    }
}
Sticky.propType = {
    height: PropTypes.number.isRequired
}
export default Sticky